
<!-- 角色管理 -->
<template>
  <div class="role_management_container">
    <div class="search_box">
      <!-- <el-button type="primary" class="fl" @click="showPopup">新增</el-button> -->
      <div class="btn btn_add" @click="showPopup('ruleForm')">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">新增</span>
      </div>
      <div  class="fr" >
        <el-input placeholder="请输入角色名称" size="small" v-model="roleName" @keyup.enter.native="searchData(roleName)">
          <div slot="append" class="btn_search" @click="searchData(roleName)">查询</div>
        </el-input>
      </div>
      <div class="clear"></div>
    </div>
    <div class="table_box special_table_box">
      <adminTable :tableHead="tableHead" :tableData="tableData"></adminTable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.curPage"
        :page-sizes="[10, 20, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalRows">
      </el-pagination>
    </div>


    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatus">
        <!-- 新增编辑页面 -->
        <div class="popup mini" v-show="popupState.popupName !== '授权'">
          <i class="el-icon-error icon_close" @click="popupState.showStatus = false"></i>
          <div class="title">{{popupState.popupName}}</div>

          <div class="content">
            <el-form :model="formData" ref="ruleForm" :rules="rules" label-position="left" :readonly="checkStatus" style=""
              label-width="90px" class="form">
              <div style="overflow:hidden">
                <el-form-item label="角色名称 : " prop="roleName" style="width: 100%" size="small" class="fl">
                  <el-input v-model="formData.roleName" autocomplete="off"  placeholder="请输入角色名称"></el-input>
                </el-form-item>
                <el-form-item label="数据权限 : " prop="dataPermissions" style="width: 100%" size="small" class="fl">
                  <el-select v-model="formData.dataPermissions" placeholder="请选择数据权限">
                    <el-option v-for="(item,key) in dataPermissionsList" :key="key" :value="item.dicCode" :label="item.dicLabel">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="备注 : " style="width: 100%" prop="remark" size="small" class="fl not_must">
                  <el-input v-model="formData.remark" autocomplete="off"></el-input>
                </el-form-item>

              </div>

            </el-form>

            <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupName == '新增角色'" @click="submitAdd('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupName == '编辑角色'" @click="submitEdit('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div>

          </div>
        </div>
        <!-- 新增编辑页面 -->

        <!-- 授权页面 -->
        <div class="popup mini" v-show="popupState.popupName == '授权'">
          <i class="el-icon-error icon_close" @click="popupState.showStatus = false"></i>
          <div class="title">{{popupState.popupName}}</div>

          <div class="content">
            <!-- <adminTable :tableHead="tableHeadSetRole" :tableData="tableDataSetRole"></adminTable> -->
            <el-tree
              ref="tree"
              node-key="menuId"
              :data="tableDataSetRole"
              show-checkbox
              :default-checked-keys="choosedRole"
              highlight-current
              check-on-click-node
              @check-change="handleCheckChange">
            </el-tree>
            
            <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupName == '授权'" @click="setRoleSubmit">
                <span class="btn_txt">保存</span>
              </div>
            </div>

          </div>
        </div>
        <!-- 授权页面 -->
        
      </div>
    </transition>
  </div>
</template>

<style>
[role=treeitem]{
  /* display: inline-block; */
}
[role=tree] > div, [role=tree] > div >  [role="group"] > div{
  /* display: block !important; */
}
</style>
<style scoped>

</style>

<script>
import adminTable from '@/components/assembly/adminTable'

import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("roleManagement");
export default {
  name: 'roleManagement',
  data() {
    return {
      roleName: '',
      roleList: [],
      checkList: [],
      checkStatus: false,
      schoolId: '',
      page: {
        curPage : 0,
        pageSize: 0,
        totalRows: 0,
      },
      formData: {
        roleName: '',
        dataPermissions: '',
      },
      dataPermissionsList: [],
      popupState: {
        showStatus: false,
        popupName: '新增角色',
      },
      tableHead: {
        // border: true,
        // order: true,
        operation_width: '300px',
        setFunction: [
          {
            fun: this.setRole,
            name: "授权",
          },
          {
            // showState: "0",
            // hideKey: "flag",
            fun: this.tableEdit,
            name: "编辑"
          },
          {
            fun: this.tableDelete,
            name: "删除"
          },
        ],
        data: [
          {
            name: '角色名称',
            key: 'roleName',
            align: 'center',
          },
          {
            name: "备注",
            key: "remark",
            align: "center"
          },
        ]
      },
      tableData: [],

      tableHeadSetRole: {
        keyId: 'menuId',
        data: [{
            name: "ID",
            key: "menuId"
          },
          {
            name: "菜单",
            key: "label",
            align: 'center',
          }
        ],
        check: [{
          id: "checked",
          fun: this.checkChange
        }]
      },
      tableDataSetRole: [],
      choosedRole: [],

      
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        dataPermissions: [
          { required: true, message: '请选择数据权限', trigger: 'change' },
        ],
      }

    }
  },
  created() {
    this.initData();
    this.initDataPermissionsList();
  },
  // watch: {
  //   mapPowerList: {
  //     handler(newName, oldName) {
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    // 获取列表
    initData(roleName) {
      roleName = roleName || this.roleName || '';
      let data = {
        roleName: roleName,
        curPage: this.page.curPage,
        pageSize: this.page.pageSize,
      }
      this.post({
        API: 'selectBmRolePageList',
        data: data
      }).then(res => {
        this.tableData = res.data;
        this.page = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    initDataPermissionsList() {
      this.formGet({
        API: 'queryByDicKey',
        data: {
          dicKey: 'dataPermissions'
        }
      }).then(res => {
        this.dataPermissionsList = res;
      })
    },

    // initRoleList() {
    //   this.formGet({
    //     API: 'queryMenuListByAccountId',
    //     data: {
    //       roleId: ''
    //     }
    //   }).then(res => {
    //     this.roleList = res.menuList;
    //     this.tableDataSetRole = res.menuList;
    //     console.log(this.roleList);
    //     this.popupState = {
    //       showStatus: true,
    //       popupName: '授权',
    //     }
    //   }).catch(err => {
    //     this.$message.error(err);
    //   })
    // },

    
    

    

    searchData(roleName) {
      this.page.curPage = 1;
      this.initData(roleName)
    },


    showPopup(formName) {
      this.formData = {}
      this.popupState = {
        showStatus: true,
        popupName: '新增角色',
      }
      this.$refs[formName].resetFields();   // 初始化

    },
    // 新增提交
    submitAdd(formName) {
      let data = this.formData;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.post({
            API: 'insert',
            data: data
          }).then(res => {
            console.log(res)
            if(res == 1) {
              this.$message.success('新建成功')
              this.initData();
              this.popupState.showStatus = false;
            }
          }).catch(err => {
            this.$message.error(err);
          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      });

      
    },

    // 编辑提交
    submitEdit(rowData) {

      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = this.formData
          data.schoolId = this.schoolId;
          this.post({
            API: 'update',
            data: data
          }).then(res => {
            this.$message.success('修改成功');
            this.initData();
            this.popupState.showStatus = false;
          }).catch(err => {
            this.$message.error(err);
          })
        }
      });

      
    },

    // 表格编辑 回显
    tableEdit(rowData) {
      this.$refs.ruleForm.resetFields();

      this.roleId = rowData.row.roleId;
      let data = {
        id: this.roleId,
      }
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        this.popupState = {
          popupName: '编辑角色',
          showStatus: true,
        }
        this.formData = res;
        
      }).catch(err => {
        // this.$message.error(err);
      })
    },

    // 表格删除
    tableDelete(rowData) {
      let roleId = rowData.row.roleId;
      let data = {
        id: roleId,
      }

      this.$confirm('是否删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteById',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });

      
      
    },

    // 授权
    setRole(rowData) {
      // this.$refs.tree.setCheckedNodes([{
      //   id: 5,
      //   label: '二级 2-1'
      // }, {
      //   id: 9,
      //   label: '三级 1-1-1'
      // }]);


      this.roleId = rowData.row.roleId
      this.formGet({
        API: 'queryMenuTreeIsChecked',
        data: {
          roleId: rowData.row.roleId  
        }
      }).then(res => {
        this.roleList = res.menuList;
        this.tableDataSetRole = res.menuList;
        this.popupState = {
          showStatus: true,
          popupName: '授权',
        }
        this.handleRoleData(this.tableDataSetRole)
      }).catch(err => {
        this.$message.error(err);
      })
    },

    handleRoleData(roleList) {
      console.log(roleList)
      let arr = [];
      let fun = function(data) {
        data.forEach((item, index) => {
          // console.log(item)
          if(item.children) {
            fun(item.children)
          }else{
            if(item.checked == true) {
              arr.push(item.menuId);
            }
          }
        })
      }
      fun(roleList)
      let checkedArr = []
      arr.forEach(item => {
        let obj = {
          menuId: item,
        }
        checkedArr.push(obj)
      })

      console.log(arr)
      console.log(checkedArr)
      // this.$refs.tree.setCheckedNodes(checkedArr);
      this.choosedRole = arr
    },

    // 提交 授权
    setRoleSubmit() {
      let roleList = this.$refs.tree.getCheckedNodes(false, true)
      let roleIdArr = []
      roleList.forEach(item => {
        roleIdArr.push(item.menuId)
      })
      this.post({
        API: 'setMenuForRole',
        data: {
          menuId: roleIdArr,
          roleId: this.roleId
        }
      }).then(res => {
        this.$message.success('授权成功');
        this.popupState.showStatus = false;
      })
    },
    
    checkChange() {

    },
    handleCheckChange(e) {
      console.log(e)
    },


    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page.curPage = val;
      this.initData();
    }
    
  },
  computed: {
    ...mapState([
    ]),
    // ...mapGetters(["selectedIds"])
  },
  components: {
    adminTable,
  },
}

</script>